package com.javaweb.proxydemo;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/9/25 8:59
 */

import com.javaweb.dao.UserDao;
import com.javaweb.dao.impl.UserDaoImpl;
import com.javaweb.model.User;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 创建代理对象工厂
 */
public class ProxyFactory {

    public static Object getProxyInstance(Object target, Method method,
                                          LogAspect logAspect) {

        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        /**
                         * 植入后的逻辑
                         */
                        Object ret = null ;
                        /**
                         * before execution, the logic could be added here.
                         */
                        logAspect.beforeExecution();
                        // join point: method execution. for instance, user.delete(1)
                        ret = method.invoke(target, args) ;
                        /**
                         * after execution, the logic could be added here also.
                         */
                        logAspect.afterExecution();

                        return ret;
                    }



                }

        ) ;
    }
    // test
    public  static void main(String args[]) throws Exception {

        UserDao userDao = new UserDaoImpl() ;

        UserDao _userDaoProxy = (UserDao) ProxyFactory.getProxyInstance(
                userDao,
                UserDao.class.getMethod("selectCountAll"),
                new LogAspect()) ;
        _userDaoProxy.selectCountAll() ;






    }


}
